package com.isyscore.os.metadata.ckschema;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.common.collect.Lists;
import com.isyscore.os.metadata.database.ClickHouseDatabase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.isyscore.os.metadata.constant.CommonConstant.DS_CK_METADATA;

/**
 * 负载对clickhouse中metadata业务所使用的表结构进行初始化操作
 */
@Component
public class MetadataDbInitializer {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String CK_DB_NAME = "isc_metadata";

    private static final String METRIC_DEMO_TABLE = "demo_device";

    private static final String METRIC_JOB_LOG_TABLE = "metric_job_batch_local";

    private static final String KETTLE_TRANS_LOG = "kettle_trans_log_local";

    private static final String METRIC_JOB_RESULT_TABLE = "metric_job_batch_result_local";

    /**
     * 使用PostConstruct因为启动顺序问题，多数据源无法正确切换，改为使用EventListener
     */
    @DS(DS_CK_METADATA)
    @EventListener
    public void initCKSchema(ContextRefreshedEvent event) {
        ClickHouseDatabase db = new ClickHouseDatabase();
        String tableListSql = db.tableListSql(CK_DB_NAME);
        List<String> tables = this.jdbcTemplate.query(tableListSql, (rs, rowNum) -> {
            String tableName = rs.getString(1);
            if (tableName != null) {
                return tableName.toUpperCase();
            }
            return "";
        });
        if (!tables.contains(METRIC_DEMO_TABLE.toUpperCase())) {
            String initSql = ResourceUtil.readUtf8Str("ckschema/isc_metadata/metric_demo_init.sql");
            executeInitSql(initSql);
        }
        if (!tables.contains(METRIC_JOB_LOG_TABLE.toUpperCase())) {
            String initSql = ResourceUtil.readUtf8Str("ckschema/isc_metadata/metric_job_log_init.sql");
            executeInitSql(initSql);
        }
        if (!tables.contains(KETTLE_TRANS_LOG.toUpperCase())) {
            String initSql = ResourceUtil.readUtf8Str("ckschema/isc_metadata/kettle_log_init.sql");
            executeInitSql(initSql);
        }
        if (!tables.contains(METRIC_JOB_RESULT_TABLE.toUpperCase())) {
            String initSql = ResourceUtil.readUtf8Str("ckschema/isc_metadata/metric_job_result_init.sql");
            executeInitSql(initSql);
        }
    }

    @DS(DS_CK_METADATA)
    private void executeInitSql(String initSql) {
        String lineSperator = System.lineSeparator();
        String[] sqlLines = initSql.split("\\r?\\n");
        List<String> statements = Lists.newArrayList();
        StringBuilder stmt = new StringBuilder();
        for (String line : sqlLines) {
            //开头是 -- 的表示注释
            if (line.trim().isEmpty() || line.startsWith("--") ||
                    StrUtil.trimStart(line).startsWith("--")) {
                continue;
            }
            stmt.append(lineSperator).append(line);
            if (line.trim().endsWith(";")) {
                statements.add(stmt.toString());
                stmt = new StringBuilder();
            }
        }
        for (String statement : statements) {
            jdbcTemplate.execute(statement);
        }
    }


}
